package com.atguigu.chapter5.sink;

import com.alibaba.fastjson.JSON;
import com.atguigu.chapter5.source.WaterSensor;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkFunction;
import org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer;
import org.apache.flink.streaming.connectors.elasticsearch6.ElasticsearchSink;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.XContentType;


import java.util.ArrayList;

/**
 * @ClassName: ESSinkDemo
 * @Description:
 * @Author: kele
 * @Date: 2021/4/5 22:40
 **/
public class ESSinkDemo {

    public static void main(String[] args){

        Configuration conf = new Configuration();
        conf.setInteger("rest.port",20000);

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(2);

        ArrayList<WaterSensor> waterSensors = new ArrayList<>();
        waterSensors.add(new WaterSensor("sensor_1", 1607527992000L, 20));
        waterSensors.add(new WaterSensor("sensor_1", 1607527994000L, 50));
        waterSensors.add(new WaterSensor("sensor_1", 1607527996000L, 50));
        waterSensors.add(new WaterSensor("sensor_2", 1607527993000L, 10));
        waterSensors.add(new WaterSensor("sensor_2", 1607527995000L, 30));

        ArrayList<HttpHost> list = new ArrayList<>();

        list.add(new HttpHost("hadoop162",9200));
        list.add(new HttpHost("hadoop163",9200));
        list.add(new HttpHost("hadoop164",9200));


        ElasticsearchSink.Builder<WaterSensor> esBuilder = new ElasticsearchSink.Builder<>(list, new ElasticsearchSinkFunction<WaterSensor>() {
            @Override
            public void process(WaterSensor waterSensor,
                                RuntimeContext runtimeContext,
                                RequestIndexer requestIndexer) {

                IndexRequest index = Requests.indexRequest()
                        .index("senion")
                        .type("_doc")
                        .id(waterSensor.getId() + waterSensor.getTs() + "")
                        .source(JSON.toJSONString(waterSensor), XContentType.JSON);

                requestIndexer.add(index);

            }
        });


        env.fromCollection(waterSensors)
                .addSink(esBuilder.build());


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


}
